<?php
/**
电影字幕翻译php脚本。
实现原理：
1、读取目标文件多行 英文语句，并去除无效语句。记录翻译行号。
2、尽可能多的组合要翻译的语句，减少 api 调用次数。
3、获取结果，利用记录行号，直接替换英文语句。
4、保存文件
*/
header("Content-type:text/html;charset=utf8");
set_time_limit(0);
//英文字幕文件
$filename = './Avengers.srt';
//翻译存储文件
$filename2 = './Avengers2.srt';
$fp = fopen($filename, 'r');
file_put_contents($filename2, '');
$fp2 = fopen($filename2, 'a+');
$file_content = $msg = '';
$i = 0;
$request_times = 0;
while($line = fgets($fp)) {
    $i++;
	$file_content[$i] = $line;
	if (trim($line) != '' && (ord(0) > ord($line[0]) || ord($line[0]) > ord(9))) {
		$line = trim(str_replace(array("-","\n", "\n\r"), "", $line));
		$msg .= $i ." ~ ,". $line . ". | ";
	}
	if ($i % 500 == 1) {
		$msg = str_replace(array("\n", "\n\r"), "", $msg);
		$msg = preg_replace("#\|\?+\|#", "", $msg);
		
		$request_times++;
		$cache_file = "./cache2/" . $request_times . "_" . md5($msg) . '.log';
		if (!is_file($cache_file)) {
			$beta_bd_translate = new Beta_bd_translate;
			$aim_message = $beta_bd_translate->translate($msg,'en', 'zh');
			file_put_contents($cache_file, $aim_message);
		} else {
			$aim_message = file_get_contents($cache_file);
		}
		$msg_data = explode("|", $msg);
		$aim_data = explode("|", $aim_message);
		foreach ($msg_data as $k => $v) {
			$aim_data[$k] = trim($aim_data[$k]);
			if (!empty($aim_data[$k]) && trim($v) && strlen($v) > 4) {
				$replace_list[$v] = $aim_data[$k];
			}
		}
		foreach ($replace_list as $search => $replace) {
			if (strpos($replace, "~") !== false) {
				$item = explode("~", $replace);
				$item[0] = intval(trim($item[0]));
				if (!isset($file_content[$item[0]]) || $item[0] == 0 || $item[0] == 1) {
				} else {
					$search = substr($search, strpos($replace, "~") + 2);
					$file_content[$item[0]] =  trim($item[1], "，") . "\n";
// 					$file_content[$item[0]] =  iconv('UTF-8', 'GBK//IGNORE', trim($item[1], "，")) . "\n";
						
				}
			}
		}
		$tmp_content = implode("", $file_content);
		$file_content = array();
// 		$tmp_content = str_replace(array_keys($replace), $replace, $file_content, $count);
// 		var_dump($tmp_content);
// 		var_dump($file_content);
// 		var_dump($replace);
		fwrite($fp2, $tmp_content);
		
		echo "<hr />";
		$msg = '';
	}
}
$msg = str_replace(array("\n", "\n\r"), "", $msg);
$msg = preg_replace("#\|\?+\|#", "", $msg);

$request_times++;
$cache_file = "./cache2/" . $request_times . "_" . md5($msg) . '.log';
if (!is_file($cache_file)) {
	$beta_bd_translate = new Beta_bd_translate;
	$aim_message = $beta_bd_translate->translate($msg,'en', 'zh');
	file_put_contents($cache_file, $aim_message);
} else {
	$aim_message = file_get_contents($cache_file);
}
$msg_data = explode("|", $msg);
$aim_data = explode("|", $aim_message);
foreach ($msg_data as $k => $v) {
	$aim_data[$k] = trim($aim_data[$k]);
	if (!empty($aim_data[$k]) && trim($v) && strlen($v) > 4) {
		$replace_list[$v] = $aim_data[$k];
	}
}
foreach ($replace_list as $search => $replace) {
	if (strpos($replace, "~") !== false) {
		$item = explode("~", $replace);
		$item[0] = intval(trim($item[0]));
		if (!isset($file_content[$item[0]]) || $item[0] == 0 || $item[0] == 1) {
		} else {
			$search = substr($search, strpos($replace, "~") + 2);
			$file_content[$item[0]] =  trim($item[1], "，") . "\n";
			// 					$file_content[$item[0]] =  iconv('UTF-8', 'GBK//IGNORE', trim($item[1], "，")) . "\n";

		}
	}
}
$tmp_content = implode("", $file_content);
$file_content = array();
// 		$tmp_content = str_replace(array_keys($replace), $replace, $file_content, $count);
// 		var_dump($tmp_content);
// 		var_dump($file_content);
// 		var_dump($replace);
fwrite($fp2, $tmp_content);

echo "<hr />";
$msg = '';



fclose($fp);
fclose($fp2);
var_dump('done', $request_times);
class Beta_bd_translate {
	
	public $APPKEY = '百度APPKEY';
	
	public function __construct() {
	}

	/**
	 * 翻译方法
	 */
	public function translate($q,$from = 'zh',$to = 'en') {
		$url = 'http://openapi.baidu.com/public/2.0/bmt/translate?client_id='.$this->APPKEY.'&from='.$from.'&to='.$to;
		$data = array('q'=>$q);
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$content = curl_exec($ch);
		curl_close($ch);
		if($content !==  false) {
			$content = json_decode($content);
			$c = $content->trans_result;
			$res = '';
			foreach ($c as $cc) {
				$res.=$cc->dst . " ";
			}
			return $res;
		}
		return array('src'=>'','ds');
	}
	
}